package writeor.aidraw.inteceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import writeor.aidraw.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class login_inteceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("运行登录的拦截器preHandle");
        String uri = request.getRequestURI();
        //判断当前请求地址是否登录地址
        if(uri.contains("login") || uri.contains("toLogin")||uri.contains("index")||uri.contains("toRegister")||uri.contains("register"))
        {
            //登录请求，直接放行
            System.out.println("登录请求，直接放行");
            return true;
        }
        else
        {
            //判断用户是否登录
            if(request.getSession().getAttribute("USER_SESSION")!=null)
            {
                //说明已经登录，放行
                System.out.println("已经登录");
                //取出session的rank存入model给侧边栏用
                User user = (User) request.getSession().getAttribute("USER_SESSION");
                if(user.getUser_rank()==1){
                    System.out.println("用户为管理员");
                    request.setAttribute("admin", "true");
                }
                return true;
            }
            else
            {
                //没有登录，重定向到登录界面
                System.out.println("用户为空，启动拦截器");
                response.sendRedirect(request.getContextPath() + "/toLogin");
            }
        }
        //默认拦截
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println("拦截器2posthandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //System.out.println("拦截器2afterhandle");
    }
}
